package com.java.example.ui.activity

import android.Manifest
import android.app.NotificationManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.provider.Settings
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.view.WindowManager
import androidx.activity.viewModels
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.whenCreated
import androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback
import com.blankj.utilcode.util.PermissionUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.SnackbarUtils
import com.blankj.utilcode.util.ToastUtils
import com.blankj.utilcode.util.UriUtils
import com.java.example.R
import com.java.example.app.Constant
import com.java.example.app.Latte
import com.java.example.base.BaseActivity
import com.java.example.bean.CameraImageBean
import com.java.example.databinding.ActivityIndexBinding
import com.java.example.ui.adapter.FragmentIndexAdapter
import com.java.example.ui.dialog.MeasureTypeDialog
import com.java.example.ui.dialog.PermissionUserDialog
import com.java.example.ui.fragment.HomeFragment
import com.java.example.ui.fragment.MessageFragment
import com.java.example.ui.fragment.PersonCenterFragment
import com.java.example.ui.fragment.ProjectManagerFragment
import com.java.example.ui.viewmodel.IndexViewModel
import com.java.example.util.Download
import com.java.example.util.PermissionGroup
import com.java.example.util.StatusBarUtil
import com.java.example.util.file.FileUtil
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File
import java.util.Hashtable
import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.CopyOnWriteArraySet
import java.util.concurrent.Executors


class MainActivity : BaseActivity<ActivityIndexBinding>(R.layout.activity_index) {
    private val viewModel: IndexViewModel by viewModels()
    var copy: CopyOnWriteArrayList<Any> = CopyOnWriteArrayList()
    var set: Set<String> = CopyOnWriteArraySet()

    private val fragmentAdapter: FragmentIndexAdapter by lazy {
        copy.add("!@3")
        copy.add(3)
        copy.getOrNull(1) as Int
        copy.toSet().toList()
        var es = Executors.newFixedThreadPool(12)
        var tt = es.submit {

        }

        tt.get()
        es.execute {

        }
        lifecycleScope
        viewModelStore
        var uu: Hashtable<String, Int> = Hashtable()

        val fragments: ArrayList<Fragment> = arrayListOf()
        fragments.add(HomeFragment())
        fragments.add(ProjectManagerFragment())
        fragments.add(MessageFragment())
        fragments.add(PersonCenterFragment())
        FragmentIndexAdapter(this, fragments)
    }
    private var currentItem = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Latte.configurator.withActivity(this)
        StatusBarUtil.setTransparentForWindow(this)
        StatusBarUtil.setDarkMode(this)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            setLayoutInCutOutThenP()
        }

        lifecycle.addObserver(Download())

        binding.click = ClickCall()
        binding.include.mPager.apply {
            setAdapter(fragmentAdapter)
            setUserInputEnabled(false)
            setOffscreenPageLimit(1)
            registerOnPageChangeCallback(MyPageChangeCallback())
            currentItem = 0
        }
        lifecycleScope.launch {
            whenCreated {

            }
            delay(2000)
            checkPermission()
        }

        val job = CoroutineScope(Dispatchers.Main).launch(start = CoroutineStart.LAZY) {
            println(1)
            delay(1000)
            println(3)
        }
        job.start()
    }

    private fun checkPermission() {
        val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        if (!manager.areNotificationsEnabled()) {
            PermissionUserDialog.create().showDialog(this, "为体验测量大师完整的消息通知功能，现申请开启通知相关权限") {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                    PermissionUtils.permission(Manifest.permission.POST_NOTIFICATIONS).callback(object : PermissionUtils.SimpleCallback {
                        override fun onGranted() {
                        }

                        override fun onDenied() {
                            ToastUtils.showShort(R.string.no_limit)
                        }
                    }).request()
                } else {
                    val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                    val uri = Uri.fromParts("package", packageName, null)
                    intent.setData(uri)
                    startActivity(intent)
                }
            }
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - viewModel.mExitTime) > 2000) {
                SnackbarUtils.with(binding.root).setMessage("再按一次退出程序").setDuration(SnackbarUtils.LENGTH_SHORT).showWarning()
                viewModel.mExitTime = System.currentTimeMillis()
            } else {
                finish()
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    @RequiresApi(api = Build.VERSION_CODES.P)
    protected fun setLayoutInCutOutThenP() {
        val lp = this.window.attributes
        lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
        this.window.setAttributes(lp)
    }

    inner class MyPageChangeCallback : OnPageChangeCallback() {
        override fun onPageSelected(position: Int) {
            super.onPageSelected(position)
            setCurrentPage(position)
        }
    }

    private fun setCurrentPage(index: Int) {
        currentItem = index
        when (index) {
            0 -> {
                binding.include.imgFirst.setImageResource(R.drawable.bottom_home_checked)
                binding.include.tvFirst.setTextColor(ContextCompat.getColor(this, R.color.mainColor))
                binding.include.imgFind.setImageResource(R.drawable.bottom_project_manager_unchecked)
                binding.include.tvFind.setTextColor(ContextCompat.getColor(this, R.color.bottom_text_color))
                binding.include.imgMap.setImageResource(R.drawable.bottom_message_unchecked)
                binding.include.tvMap.setTextColor(ContextCompat.getColor(this, R.color.bottom_text_color))
                binding.include.imgMine.setImageResource(R.drawable.bottom_me_unchecked)
                binding.include.tvMine.setTextColor(ContextCompat.getColor(this, R.color.bottom_text_color))
            }

            1 -> {
                binding.include.imgFirst.setImageResource(R.drawable.bottom_home_unchecked)
                binding.include.tvFirst.setTextColor(ContextCompat.getColor(this, R.color.bottom_text_color))
                binding.include.imgFind.setImageResource(R.drawable.bottom_project_manager_checked)
                binding.include.tvFind.setTextColor(ContextCompat.getColor(this, R.color.mainColor))
                binding.include.imgMap.setImageResource(R.drawable.bottom_message_unchecked)
                binding.include.tvMap.setTextColor(ContextCompat.getColor(this, R.color.bottom_text_color))
                binding.include.imgMine.setImageResource(R.drawable.bottom_me_unchecked)
                binding.include.tvMine.setTextColor(ContextCompat.getColor(this, R.color.bottom_text_color))
            }

            2 -> {
                binding.include.imgFirst.setImageResource(R.drawable.bottom_home_unchecked)
                binding.include.tvFirst.setTextColor(ContextCompat.getColor(this, R.color.bottom_text_color))
                binding.include.imgFind.setImageResource(R.drawable.bottom_project_manager_unchecked)
                binding.include.tvFind.setTextColor(ContextCompat.getColor(this, R.color.bottom_text_color))
                binding.include.imgMap.setImageResource(R.drawable.bottom_message_checked)
                binding.include.tvMap.setTextColor(ContextCompat.getColor(this, R.color.mainColor))
                binding.include.imgMine.setImageResource(R.drawable.bottom_me_unchecked)
                binding.include.tvMine.setTextColor(ContextCompat.getColor(this, R.color.bottom_text_color))
            }

            3 -> {
                binding.include.imgFirst.setImageResource(R.drawable.bottom_home_unchecked)
                binding.include.tvFirst.setTextColor(ContextCompat.getColor(this, R.color.bottom_text_color))
                binding.include.imgFind.setImageResource(R.drawable.bottom_project_manager_unchecked)
                binding.include.tvFind.setTextColor(ContextCompat.getColor(this, R.color.bottom_text_color))
                binding.include.imgMap.setImageResource(R.drawable.bottom_message_unchecked)
                binding.include.tvMap.setTextColor(ContextCompat.getColor(this, R.color.bottom_text_color))
                binding.include.imgMine.setImageResource(R.drawable.bottom_me_checked)
                binding.include.tvMine.setTextColor(ContextCompat.getColor(this, R.color.mainColor))
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == viewModel.REQUEST_CODE && resultCode == RESULT_OK) {
            if (data != null) {
                Log.e("hwx", "单选模式")
                viewModel.doNext(this, data.data, true)
            }
        } else if (requestCode == viewModel.REQUEST_CODE_TAKE && resultCode == RESULT_OK) {
            lifecycleScope.launch {
                delay(50)
                viewModel.doNext(this@MainActivity, CameraImageBean.instance.path!!, false)
                //保存到系统相册 begin
                val tt = MediaStore.Images.Media.insertImage(contentResolver, UriUtils.uri2File(CameraImageBean.instance.path!!).path, "MyImage", null)
                val mediaScanIntent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
//                val contentUri = Uri.fromFile(UriUtils.uri2File(CameraImageBean.instance.path!!))
                mediaScanIntent.setData(UriUtils.file2Uri(File(tt)))
                sendBroadcast(mediaScanIntent)
                //保存到系统相册 end
            }
        }
    }


    inner class ClickCall {
        fun tabOne(context: Context, view: View) {
            setCurrentPage(0)
            binding.include.mPager.setCurrentItem(currentItem, false)
        }

        fun tabTwo(context: Context, view: View) {
            setCurrentPage(1)
            binding.include.mPager.setCurrentItem(currentItem, false)
        }

        fun tabThree(context: Context, view: View) {
            setCurrentPage(2)
            binding.include.mPager.setCurrentItem(currentItem, false)
        }

        fun tabFour(context: Context, view: View) {
            setCurrentPage(3)
            binding.include.mPager.setCurrentItem(currentItem, false)
        }

        fun center(context: Context, view: View) {//拍照测量
            //这里不能选择门窗，放在里面选择
            if (viewModel.measureTypeDialog == null) {
                viewModel.measureTypeDialog = MeasureTypeDialog.create(this@MainActivity)
                viewModel.measureTypeDialog!!.setOnActionListener(object : MeasureTypeDialog.OnActionListener {
                    override fun onChooseType(type: Int) {
                        viewModel.measureType = type
                        if (viewModel.measureType == 115) {
                            val intent = Intent(Intent.ACTION_GET_CONTENT)
                            intent.setType("image/*")
                            intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, false)
                            startActivityForResult(Intent.createChooser(intent, "选择图片"), viewModel.REQUEST_CODE)
                        } else {
                            val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                            val tempFile = File(getExternalFilesDir(Constant.PIC_FILES_DIR_TEMP), FileUtil.getFileNameByTime("IMG", "jpg"))
                            val uri = FileProvider.getUriForFile(this@MainActivity, packageName + ".provider", tempFile)
                            CameraImageBean.instance.path = uri
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri)
                            startActivityForResult(intent, viewModel.REQUEST_CODE_TAKE)
                        }
                    }
                })
            }
            var isLuo = 1
            if (PermissionUtils.isGranted(*PermissionGroup.permissionFileAndCamera)) {
                viewModel.measureTypeDialog!!.showDialog(this@MainActivity, "裸测", "拍照测量", "", isLuo, 0, true)
            } else {
                PermissionUserDialog.create().showDialog(this@MainActivity, "为体验测量大师完整的测量功能，现申请开启相机和存储权限") {
                    PermissionUtils.permission(*PermissionGroup.permissionFileAndCamera).callback(object : PermissionUtils.SimpleCallback {
                        override fun onGranted() {
                            viewModel.measureTypeDialog!!.showDialog(this@MainActivity, "裸测", "拍照测量", "", isLuo, 0, true)
                        }

                        override fun onDenied() {
                            ToastUtils.showShort(R.string.no_limit)
                        }
                    }).request()
                }
            }
        }
    }
}
